﻿using System;
using System.Threading;


#if NETSTANDARD2_0

using System.Collections.Concurrent;

#endif
#if NET35
using System.Runtime.Remoting.Messaging;
#endif

namespace Kernelx.Common.Threading
{
    /// <summary>
    /// 定义并发安全操作的访问容器
    /// </summary>
    public static class ConcurrentContainer
    {

        private static readonly Action<string, object> _setData;
        private static readonly Func<string, object> _getData;


#if NET35
        static ConcurrentContainer()
        {
            _setData = CallContext.SetData;
            _getData = CallContext.GetData;
        }
#endif    

#if NETSTANDARD2_0
        private static readonly ConcurrentDictionary<string, AsyncLocal<object>> state = new ConcurrentDictionary<string, AsyncLocal<object>>();
        static ConcurrentContainer()
        {

            _setData = (name, data) => state.GetOrAdd(name, _ => new AsyncLocal<object>()).Value = data;
            _getData = name => state.TryGetValue(name, out AsyncLocal<object> data) ? data.Value : null;
        }
#endif

        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="data"></param>
        public static void SetData(string name, object data) => _setData(name, data);

        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static object GetData(string name) => _getData(name);


    }

}
